 //
//  IapHelper.swift
//  sonic
//
//  Created by 魔码传媒 on 29/12/2017.
//  Copyright © 2017 magicode. All rights reserved.
//

import Foundation
import StoreKit
 
protocol IapDelegate{
    //代理方法
    func didFinishIap(status:Bool)
 }

class IapHelper : NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver
{
    var delegate:IapDelegate?
    
    /* Variables */
    let COIN_PRODUCT_IDS = Set(["com.mgc.koe.money.18", "com.mgc.koe.money.68", "com.mgc.koe.money.158", "com.mgc.koe.money.298", "com.mgc.koe.money.518", "com.mgc.koe.money.998", "com.mgc.koe.money.1198", "com.mgc.koe.money.1998", "com.mgc.koe.money.3998"])
    
    let ARRAY_COIN_PRODUCT_IDS = ["com.mgc.koe.money.18", "com.mgc.koe.money.68", "com.mgc.koe.money.158", "com.mgc.koe.money.298", "com.mgc.koe.money.518", "com.mgc.koe.money.998", "com.mgc.koe.money.1198", "com.mgc.koe.money.1998", "com.mgc.koe.money.3998"]
    
    var productID = ""
    var productsRequest = SKProductsRequest()
    static var iapProducts = [SKProduct]()
    
    var selectedIapProducts:SKProduct? = nil
    
    override init() {
        super.init()
        // Fetch IAP Products available
        
//        if IapHelper.iapProducts.count < 1{
//            fetchAvailableProducts()
//        }
    }
    
    // MARK: - FETCH AVAILABLE IAP PRODUCTS
    func fetchAvailableProducts(product:String)  {
        // Put here your IAP Products ID's
        let productIdentifiers = Set([product])
        productsRequest = SKProductsRequest(productIdentifiers:
            productIdentifiers)
        productsRequest.delegate = self
        productsRequest.start()
    }
    
    // MARK: - FETCH AVAILABLE IAP PRODUCTS
    func fetchAvailableProducts()  {
        productsRequest = SKProductsRequest(productIdentifiers:
            COIN_PRODUCT_IDS)
        productsRequest.delegate = self
        productsRequest.start()
    }
    
    // MARK: - REQUEST IAP PRODUCTS
    func productsRequest (_ request:SKProductsRequest, didReceive response:SKProductsResponse) {
        if (response.products.count > 0) {
//            IapHelper.iapProducts = response.products
            selectedIapProducts = response.products[0]
            purchaseMyProduct(product: selectedIapProducts!)
            
//            // 1st IAP Product (Consumable) ------------------------------------
//            let firstProduct = response.products[0] as SKProduct
//
//            // Get its price from iTunes Connect
//            let numberFormatter = NumberFormatter()
//            numberFormatter.formatterBehavior = .behavior10_4
//            numberFormatter.numberStyle = .currency
//            numberFormatter.locale = firstProduct.priceLocale
//            let price1Str = numberFormatter.string(from: firstProduct.price)
//
//            // Show its description
//            let text1 = firstProduct.localizedDescription + "\nfor just \(price1Str!)"
//            // ------------------------------------------------
            
            /* 2nd IAP Product (Non-Consumable) ------------------------------
            let secondProd = response.products[1] as SKProduct
            // Get its price from iTunes Connect
            numberFormatter.locale = secondProd.priceLocale
            let price2Str = numberFormatter.string(from: secondProd.price)
            // Show its description
            nonConsumableLabel.text = secondProd.localizedDescription + "\nfor just \(price2Str!)"
            // ------------------------------------ */
            
            
        }
    }
    
    //从数组取出需要的id
    func productSelector(price:Int) -> String?
    {
        var product = ARRAY_COIN_PRODUCT_IDS.filter(){
            return $0.characters.split(separator: ".").map(String.init).last == String(price) //$0.contains(String(price))
        }
        
        guard product.count > 0 else {
            return nil
        }
        
        return product[0]
    }
    
//    func productSelector(price:Int) -> SKProduct?
//    {
//        guard IapHelper.iapProducts.count > 0 else {
//            return nil
//        }
//
//        var product = IapHelper.iapProducts.filter(){
//            return $0.price.intValue == price
//        }
//
//        guard product.count > 0 else {
//            return nil
//        }
//
//        return product[0]
//    }
    
    // MARK: - MAKE PURCHASE OF A PRODUCT
    func canMakePurchases() -> Bool {  return SKPaymentQueue.canMakePayments()  }
    func purchaseMyProduct(product: SKProduct) {
        if self.canMakePurchases() {
            let payment = SKPayment(product: product)
            SKPaymentQueue.default().add(self)
            SKPaymentQueue.default().add(payment)
            
            productID = product.productIdentifier
            
            print("PRODUCT TO PURCHASE: \(product.productIdentifier) ID: \(productID)")
            
            // IAP Purchases dsabled on the Device
        } else {
            UIAlertView(title: "支付失败",
                        message: "应用内购在您的设备上被禁用！",
                        delegate: nil, cancelButtonTitle: "好").show()
        }
    }
    
    //发起支付
    func purchase(price:Int)
    {
        let strPorduct = productSelector(price: price)
        fetchAvailableProducts(product: strPorduct!)
    }
    
    // MARK:- IAP PAYMENT QUEUE
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction:AnyObject in transactions {
            if let trans = transaction as? SKPaymentTransaction {
                switch trans.transactionState {
                    
                case .purchased:
                    SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
                    
                    // The Consumable product (10 coins) has been purchased -> gain 10 extra coins!
                    if COIN_PRODUCT_IDS.contains(productID) {
                        // Add 10 coins and save their total amount
                        self.delegate?.didFinishIap(status: true)
                        
//                        UIAlertView(title: "IAP Tutorial",
//                                    message: "You've successfully bought 10 extra coins!",
//                                    delegate: nil,
//                                    cancelButtonTitle: "OK").show()
                        
                        // The Non-Consumable product (Premium) has been purchased!
                    } else {
                        self.delegate?.didFinishIap(status: false)
//                        UIAlertView(title: "IAP Tutorial",
//                                    message: "You've successfully unlocked the Premium version!",
//                                    delegate: nil,
//                                    cancelButtonTitle: "OK").show()
                    }
                    break
                    
                case .failed:
                    SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
                    self.delegate?.didFinishIap(status: false)
                    break
                case .restored:
                    SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
                    self.delegate?.didFinishIap(status: true)
                    break
                    
                default: break
                }}}
    }
    
}
